#!/bin/bash
#Author: YangYi
#Date: 2025-06-15
#Version: v1
#Content: 创建ds和svc资源


# ---------------------------初始化全局变量----------------------------

NGINXVERSION="1.13.10"
SERVICESNAME="service-availability-detection"



# ----------------------------功能模块函数-----------------------------

create_DaemonSet() {

# 创建DaemonSet
kubectl apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: $SERVICESNAME-sa
  namespace: default

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: $SERVICESNAME-role
rules:
- apiGroups: [""]
  resources: ["pods", "services", "endpoints"]
  verbs: ["get", "list", "watch"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: $SERVICESNAME-binding
subjects:
- kind: ServiceAccount
  name: $SERVICESNAME-sa
  namespace: default
roleRef:
  kind: ClusterRole
  name: $SERVICESNAME-role
  apiGroup: rbac.authorization.k8s.io

---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: $SERVICESNAME-ds
  namespace: default
spec:
  selector:
    matchLabels:
      app: nginx-redial
  template:
    metadata:
      labels:
        app: nginx-redial
    spec:
      serviceAccountName: $SERVICESNAME-sa 
      hostNetwork: true
      dnsPolicy: ClusterFirstWithHostNet
      containers:
      - name: nginx
        image: hub.paas/base/nginx:$NGINXVERSION
        ports:
        - containerPort: 80
EOF

# 创建Service
kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: $SERVICESNAME-svc
  namespace: default
spec:
  selector:
    app: nginx-redial
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: ClusterIP
EOF

echo "资源创建完成..."

}


delete_DaemonSetAndService() {
  echo "资源清理中..."
    kubectl delete ds $SERVICESNAME-ds
    kubectl delete svc $SERVICESNAME-svc
    kubectl delete ServiceAccount $SERVICESNAME-sa
    kubectl delete ClusterRole $SERVICESNAME-role
    kubectl delete ClusterRoleBinding $SERVICESNAME-binding
  echo "资源清理完成..."
}


create_DaemonSet
#sleep 30
#delete_DaemonSetAndService






